// 语言包文件 - 从JSON文件加载翻译数据
let translations = {};
let isTranslationsLoaded = false;
const translationsLoadCallbacks = [];

// 从JSON文件加载翻译数据
function loadTranslations() {
    return new Promise((resolve, reject) => {
        if (isTranslationsLoaded) {
            resolve(translations);
            return;
        }

        const xhr = new XMLHttpRequest();
        xhr.open('GET', '/static/js/translations.json', true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        
        xhr.onload = function() {
            if (xhr.status === 200) {
                try {
                    translations = JSON.parse(xhr.responseText);
                    isTranslationsLoaded = true;
                    window.translations = translations;
                    
                    // 执行所有等待的回调
                    translationsLoadCallbacks.forEach(callback => {
                        try {
                            callback(translations);
                        } catch (err) {
                            console.error('Translation callback error:', err);
                        }
                    });
                    
                    resolve(translations);
                } catch (e) {
                    console.error('Failed to parse translations JSON:', e);
                    reject(e);
                }
            } else {
                console.error('Failed to load translations file. Status:', xhr.status);
                reject(new Error(`Failed to load translations file. Status: ${xhr.status}`));
            }
        };
        
        xhr.onerror = function() {
            console.error('Error loading translations file');
            reject(new Error('Network error while loading translations file'));
        };
        
        xhr.send();
    });
}

// 导出语言包和相关方法
window.translations = translations;

// 加载翻译数据并返回Promise
window.loadTranslations = loadTranslations;

// 注册翻译加载完成后的回调
window.onTranslationsLoaded = function(callback) {
    if (isTranslationsLoaded) {
        // 如果已经加载完成，立即执行回调
        setTimeout(() => callback(translations), 0);
    } else {
        // 否则添加到等待队列
        translationsLoadCallbacks.push(callback);
    }
};

// 获取所有支持的语言代码
window.getSupportedLanguages = function() {
    return Object.keys(translations);
};

// 获取特定语言的名称
window.getLanguageName = function(langCode) {
    return translations[langCode] ? translations[langCode].langName : langCode;
};

// 初始化时自动加载翻译数据
loadTranslations().catch(err => {
    console.error('Failed to initialize translations:', err);
    // 如果加载失败，使用默认的基本翻译以确保系统可用
    translations = {
        zh: { systemName: '伊善齐商店管理系统', langName: '中文' },
        uy: { systemName: 'ئىشەنچ دۇكان باشقۇرۇش سېستىمىسى', langName: 'ئۇيغۇرچە' }
    };
    window.translations = translations;
    isTranslationsLoaded = true;
});

// 添加window.updateUIWithTranslations函数实现
window.updateUIWithTranslations = function() {
    const currentLang = window.currentLang || 'zh';
    const translations = window.translations || {};
    const langTranslations = translations[currentLang] || {};
    // console.log('当前语言:', currentLang);
    // console.log('当前语言翻译:', langTranslations);
    
    // 更新侧边栏导航
    document.querySelectorAll('[data-translate="settle"]').forEach(element => {
        element.textContent = langTranslations['settle'] || '结算管理';
    });
    document.querySelectorAll('[data-translate="settle_item"]').forEach(element => {
        element.textContent = langTranslations['settle_item'] || '结算管理';
    });
    document.querySelectorAll('[data-translate="settle_detail"]').forEach(element => {
        element.textContent = langTranslations['settle_detail'] || '结算管理';
    });
    document.querySelectorAll('[data-translate="products"]').forEach(element => {
        element.textContent = langTranslations['products'] || '商品管理';
    });
    document.querySelectorAll('[data-translate="add"]').forEach(element => {
        element.textContent = langTranslations['add'] || '商品管理';
    });
    document.querySelectorAll('[data-translate="settings"]').forEach(element => {
        element.textContent = langTranslations['settings'] || '系统设置';
    });
    document.querySelectorAll('[data-translate="warning"]').forEach(element => {
        element.textContent = langTranslations['warning'] || '库存警告';
    });
    document.querySelectorAll('[data-translate="expiry_warning"]').forEach(element => {
        element.textContent = langTranslations['expiryWarning'] || '近效期警告';
    });
    document.querySelectorAll('[data-translate="storeZhNameLable"]').forEach(element => {
        element.textContent = langTranslations['storeNameZhLabel'] || '店铺汉语名称';
    });
    document.querySelectorAll('[data-translate="storeUyNameLable"]').forEach(element => {
        element.textContent = langTranslations['storeUyNameLable'] || '店铺维吾尔语名称';
    });
    // 统一处理所有带 data-translate-placeholder 属性的元素，实现 placeholder 文本切换
    document.querySelectorAll('[data-translate="storeUyNameLable"]').forEach(input => {
        const key = input.getAttribute('data-translate="storeUyNameLable"');
        input.placeholder = langTranslations['storeUyNameLable'] || input.placeholder;
    });
    document.querySelectorAll('[data-translate="storeZhNameLable"]').forEach(input => {
        const key = input.getAttribute('data-translate="storeZhNameLable"');
        input.placeholder = langTranslations['storeZhNameLable'] || input.placeholder;
    });
    document.querySelectorAll('[data-translate="confirmChangeBtn"]').forEach(element => {
        element.textContent = langTranslations['confirmChangeBtn'] || '确认修改';
    });
    // 退出登录按钮在HTML中没有直接的data-translate属性，可能需要特殊处理
    // 如果需要添加翻译，可以为退出登录链接添加data-translate属性
    
    // 更新系统信息卡片
    document.querySelectorAll('[data-translate="system_info"]').forEach(element => {
        element.textContent = langTranslations['systemStatsTitle'] || '系统统计信息';
    });
    document.querySelectorAll('[data-translate="total_products"]').forEach(element => {
        element.textContent = langTranslations['totalProducts'] || '商品总数';
    });
    document.querySelectorAll('[data-translate="stock_warning"]').forEach(element => {
        element.textContent = langTranslations['warningProducts'] || '库存警告';
    });
    document.querySelectorAll('[data-translate="stock_zero"]').forEach(element => {
        element.textContent = langTranslations['outOfStock'] || '库存为零';
    });
    document.querySelectorAll('[data-translate="today_transaction"]').forEach(element => {
        element.textContent = langTranslations['todayTransactions'] || '今日交易';
    });
    document.querySelectorAll('[data-translate="transaction_amount"]').forEach(element => {
        element.textContent = langTranslations['todayTransactionAmount'] || '交易金额';
    });
    
    // 更新结算界面
    document.querySelectorAll('[data-translate="start_settle"]').forEach(element => {
        element.textContent = langTranslations['startSettlement'] || '开始商品结算';
    });
    document.querySelectorAll('[data-translate="cart_title"]').forEach(element => {
        element.textContent = langTranslations['cartTitle'] || '购物车';
    });
    document.querySelectorAll('[data-translate="product_barcode"]').forEach(element => {
        element.textContent = langTranslations['productBarcodeLabel'] || '商品条码';
    });
    document.querySelectorAll('[data-translate="product_name"]').forEach(element => {
        element.textContent = langTranslations['productNameLabel'] || '商品名称';
    });
    document.querySelectorAll('[data-translate="unit"]').forEach(element => {
        element.textContent = langTranslations['productUnitLabel'] || '单位';
    });
    document.querySelectorAll('[data-translate="unit_price"]').forEach(element => {
        element.textContent = langTranslations['productPriceLabel'] || '单价';
    });
    document.querySelectorAll('[data-translate="quantity"]').forEach(element => {
        element.textContent = langTranslations['quantity'] || '数量';
    });
    document.querySelectorAll('[data-translate="amount"]').forEach(element => {
        element.textContent = langTranslations['price'] || '金额';
    });
    document.querySelectorAll('[data-translate="total"]').forEach(element => {
        element.textContent = langTranslations['total'] || '合计';
    });
    document.querySelectorAll('[data-translate="clear_cart"]').forEach(element => {
        element.textContent = langTranslations['clearAll'] || '一键清零';
    });
    document.querySelectorAll('[data-translate="settleBill"]').forEach(element => {
        element.textContent = langTranslations['settleBill'] || '结算';
    });
    
    // 更新结算记录
    document.querySelectorAll('[data-translate="transaction_records"]').forEach(element => {
        element.textContent = langTranslations['transactionRecordsTitle'] || '结算记录';
    });
    
    // 更新搜索区域
    document.querySelectorAll('[data-translate-placeholder="search_transaction_no"]').forEach(input => {
        input.placeholder = langTranslations['searchPlaceholder'] || '输入流水号查询';
    });
    document.querySelectorAll('[data-translate="search"]').forEach(element => {
        element.textContent = langTranslations['searchButton'] || '查询';
    });
    document.querySelectorAll('[data-translate="reset"]').forEach(element => {
        element.textContent = langTranslations['resetButton'] || '重置';
    });
    
    // 更新表格列
    document.querySelectorAll('[data-translate="transaction_no"]').forEach(element => {
        element.textContent = langTranslations['transactionNoHeader'] || '流水号';
    });
    document.querySelectorAll('[data-translate="transaction_time"]').forEach(element => {
        element.textContent = langTranslations['transactionTimeHeader'] || '交易时间';
    });
    document.querySelectorAll('[data-translate="total_amount"]').forEach(element => {
        element.textContent = langTranslations['totalAmountHeader'] || '总金额';
    });
    document.querySelectorAll('[data-translate="operation"]').forEach(element => {
        element.textContent = langTranslations['operationHeader'] || '操作';
    });
    
    // 更新其他文本
    document.querySelectorAll('[data-translate="no_records"]').forEach(element => {
        element.textContent = langTranslations['noRecords'] || '暂无记录';
    });
    document.querySelectorAll('[data-translate="pagination_info"]').forEach(element => {
        element.textContent = langTranslations['paginationInfo'] || '显示 1-0 条，共 0 条';
    });
    
    // 更新商品表单
    document.querySelectorAll('[data-translate="product_price"]').forEach(element => {
        element.textContent = langTranslations['productPriceLabel'] || '商品价格';
    });
    document.querySelectorAll('[data-translate="product_unit"]').forEach(element => {
        element.textContent = langTranslations['productUnitLabel'] || '商品单位';
    });
    document.querySelectorAll('[data-translate="stock_quantity"]').forEach(element => {
        element.textContent = langTranslations['productStockLabel'] || '库存数量';
    });
    document.querySelectorAll('[data-translate="expiry_date"]').forEach(element => {
        element.textContent = langTranslations['expiryDateLabel'] || '失效期';
    });
    document.querySelectorAll('[data-translate="add_product"]').forEach(element => {
        element.textContent = langTranslations['addProductSubmit'] || '添加商品';
    });
    document.querySelectorAll('[data-translate="save_changes"]').forEach(element => {
        element.textContent = langTranslations['modifyProductSubmit'] || '保存修改';
    });
    
    // 更新输入框标题
    document.querySelectorAll('[data-translate-title="enter_13_digit_barcode"]').forEach(input => {
        input.title = langTranslations['invalidBarcode'] || '请输入13位数字商品条码';
    });
    
    // 更新输入框占位符
    document.querySelectorAll('[data-translate-placeholder="example_price"]').forEach(input => {
        input.placeholder = langTranslations['priceExample'] || '例如: 2.5';
    });
    
    // 更新分页控件
    document.querySelectorAll('[data-translate="previous_page"]').forEach(element => {
        element.textContent = langTranslations['prevPage'] || '上一页';
    });
    document.querySelectorAll('[data-translate="next_page"]').forEach(element => {
        element.textContent = langTranslations['nextPage'] || '下一页';
    });
    document.querySelectorAll('[data-translate="page_info"]').forEach(element => {
        element.textContent = langTranslations['page'] || '1 页 共 1 页';
    });
        
    // 处理文本方向
    if (langTranslations['textDirection'] === 'rtl') {
        document.body.classList.add('rtl');
        document.querySelectorAll('table').forEach(table => {
            table.classList.add('table-rtl');
        });
    } else {
        document.body.classList.remove('rtl');
        document.querySelectorAll('table').forEach(table => {
            table.classList.remove('table-rtl');
        });
    }
    
    // 确保购物车组件重新渲染
    if (window.UIModule && window.UIModule.renderCart) {
        window.UIModule.renderCart();
    }
};

// 确保在页面加载时执行一次翻译
window.addEventListener('DOMContentLoaded', function() {
    window.updateUIWithTranslations();
});


// 页面加载完成后初始化语言设置
$(document).ready(function() {
    // 确保翻译数据已加载
    window.onTranslationsLoaded(() => {
        // 如果有已保存的语言偏好，使用它，否则使用默认语言'zh'
        const savedLang = localStorage.getItem('currentLang') || 'zh';
        currentLang = savedLang;
        
        // 尝试应用当前语言设置
        function applyLanguageSetting() {
            if (typeof window.switchLanguage === 'function') {
                // console.log('使用window.switchLanguage应用语言设置');
                window.switchLanguage(savedLang);
                return true;
            } else if (typeof window.LanguageModule !== 'undefined' && typeof window.LanguageModule.switchLanguage === 'function') {
                console.log('使用window.LanguageModule.switchLanguage应用语言设置');
                window.LanguageModule.switchLanguage(savedLang);
                return true;
            }
            return false;
        }
        
        // 立即尝试应用语言设置
        if (!applyLanguageSetting()) {
            // 如果立即调用失败，设置一个定时器尝试多次，确保有足够时间加载模块
            console.log('尝试延迟应用语言设置...');
            let attempts = 0;
            const maxAttempts = 5;
            const delay = 300;
            
            const timer = setInterval(() => {
                attempts++;
                console.log(`尝试应用语言设置 (${attempts}/${maxAttempts})...`);
                
                if (applyLanguageSetting() || attempts >= maxAttempts) {
                    clearInterval(timer);
                    if (attempts >= maxAttempts) {
                        console.warn('多次尝试后仍未能找到switchLanguage函数，将直接更新UI翻译');
                        // 作为后备方案，直接更新UI翻译
                        if (typeof window.updateUIWithTranslations === 'function') {
                            window.updateUIWithTranslations();
                        }
                    }
                }
            }, delay);
        }
    });
});